<template>
  <div class="look_time" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="source">
                  <span class = "condi">{{$t('report.imReportFrom')}}</span>
                  <!-- <el-select size="mini"
                             v-model.trim="fromUrl"
                             multiple
                             filterable
                             :placeholder="$t('report.imReportFrom')">
                      <el-option v-for="item in fromUrlList"
                                :key="item._id"
                                :label="item.urlTitle"
                                :value="item._id"></el-option></el-select></div> -->
                  <m7Select class="el-select" filterable multiple :options="fromUrlList" v-model="fromUrl" :defaultProps="showObj"></m7Select>
                </div>
                <div class="source">
                  <el-row>
                    <el-col class="condi">
                      <span>{{$t('report.imReportArea')}}</span>
                    </el-col>
                    <el-col :span="10" class="provin">
                      <el-select size="mini"
                             v-model.trim="area"
                             multiple
                             filterable
                             :placeholder="$t('report.pleasePro')">
                        <el-option v-for="(item, index) in province"
                                   :label="item"
                                   :value="item"
                                   :key="index"></el-option></el-select>
                    </el-col>
                  </el-row>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button class="primary_btn fr turnCha" @click.stop="changeHighChartsType">{{chart}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="table">
          <el-table :data="tableData"
                    stripe
                    size="mini"
                    style="width: 100%">
            <el-table-column prop="guest"
                             :label="$t('report.imTimeInterval')"></el-table-column>
            <el-table-column prop="onlyGuest"
                             :label="$t('report.imOnlyVisiteNum')"></el-table-column>
            <el-table-column prop="Proportion"
                             :label="$t('report.imReportRatio')"></el-table-column></el-table>
        </div>
      </div>
    </div>
    <el-dialog modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../../ui-modules/unfold/index.vue'
  // import AreaLinkage from '@/components/ui-modules/area-linkage/AreaLinkage.vue'
  import dateTime from '../../base/datetime.vue'
  // import reportTable from '../../base/reportTable.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import { exportReportPdf, checkTime, searchTime, colorConfigArr } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'look_time',
    data () {
      return {
        showObj: {
          value: '_id',
          label: 'urlTitle'
        },
        isFold: false,
        fromUrl: [],
        area: [],
        province: ['上海', '浙江', '西沙群岛', '澳门', '台湾', '甘肃', '香港', '宁夏', '陕西', '安徽', '湖北', '广东', '福建', '北京', '河北', '山东', '天津', '江苏', '海南', '青海', '吉林', '西藏', '新疆', '河南', '内蒙古', '黑龙江', '云南', '广西', '辽宁', '四川', '重庆', '贵州', '湖南', '山西', '江西'],
        chart: this.$t('report.imReportLine'),
        selectedAgentList: [],
        fromUrlList: [],
        id: 'im_loyalty_report_recentlyVisited',
        title: this.$t('report.imRecentLookTime'),
        loading: false,
        timeType: 'day',
        query: {
        },
        dialogVisible: false,
        serverData: [],
        headOptions: { Config: [], data: [] },
        highchartsDefaultOptions: {
          chart: {
            type: 'column',
            animation: false
          },
          colors: colorConfigArr,
          xAxis: {
            type: 'category'
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: {
            text: this.$t('report.imRecentLookTime')
          },
          legend: { enabled: false },
          tooltip: {
            headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
            pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b><br/>'
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime
      // reportTable
      // ,
      // AreaLinkage
    },
    computed: {
      tableData () {
        return this.getTableData(this.serverData)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let datas = this.serverData
        let seriesArray = [{
          name: this.$t('report.imOnlyVisiteNum'),
          data: []
        }]

        for (let i = 0; i < datas.length; i++) {
          if (datas[i]._id === 'todayRecentlyVisited') {
            seriesArray[0].data.push({
              name: this.$t('report.imDailyNewVisite'),
              y: datas[i].count
            })
          }
          if (datas[i]._id === 'yesterdayRecentlyVisited') {
            seriesArray[0].data.push({
              name: this.$t('report.imADayVisite'),
              y: datas[i].count
            })
          }
          if (datas[i]._id === 'threeDayRecentlyVisited') {
            seriesArray[0].data.push({
              name: this.$t('report.imRecentThreeDays'),
              y: datas[i].count
            })
          }
          if (datas[i]._id === 'sevenDayRecentlyVisited') {
            seriesArray[0].data.push({
              name: this.$t('report.imThisOneWeek'),
              y: datas[i].count
            })
          }
          if (datas[i]._id === 'monthRecentlyVisited') {
            seriesArray[0].data.push({
              name: this.$t('report.imThisOneMonth'),
              y: datas[i].count
            })
          }
        }

        options.series = seriesArray
        return options
      }
    },
    methods: {
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }
        let datas = deepClone(serverData)
        let data = []
        let allNum = 0
        for (let i = 0; i < datas.length; i++) {
          allNum += datas[i].count
        }
        datas.map((item, index) => {
          if (item._id === 'todayRecentlyVisited') {
            data.push({
              guest: this.$t('report.imDailyNewVisite'),
              onlyGuest: item.count,
              Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
            })
          }
          if (item._id === 'yesterdayRecentlyVisited') {
            data.push({
              guest: this.$t('report.imADayVisite'),
              onlyGuest: item.count,
              Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
            })
          }
          if (item._id === 'threeDayRecentlyVisited') {
            data.push({
              guest: this.$t('report.imRecentThreeDays'),
              onlyGuest: item.count,
              Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
            })
          }
          if (item._id === 'sevenDayRecentlyVisited') {
            data.push({
              guest: this.$t('report.imThisOneWeek'),
              onlyGuest: item.count,
              Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
            })
          }
          if (item._id === 'monthRecentlyVisited') {
            data.push({
              guest: this.$t('report.imThisOneMonth'),
              onlyGuest: item.count,
              Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
            })
          }
        })
        return data
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      getSearchQueryData () {
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: {
            reportType: this.id,
            area: this.area,
            fromUrl: this.fromUrl

          }
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }
        this.$store.dispatch('queryLoyaltyReport', queryData).then((res) => {
          if (res.success) {
            this.serverData = deepClone(res.data)
            this.$store.dispatch('getFromUrlList', queryData).then((res) => {
              this.fromUrlList = res.fromUrlList
            })
          }
        })
      },
      exportXlsx () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }
        this.$store.dispatch('queryLoyaltyReport', queryData).then((res) => {
          if (res.success) {
            var serverData = deepClone(res.data)

            var headOptions = [
              {
                name: this.$t('report.imTimeInterval'),
                prop: 'guest'
              },
              {
                name: this.$t('report.imOnlyVisiteNum'),
                prop: 'onlyGuest'
              },
              {
                name: this.$t('report.imReportRatio'),
                prop: 'Proportion'
              }
            ]
            var tableData = this.getTableData(serverData)

            var dh = XlsxUtil.getDownloadHelper(headOptions, tableData)
            var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
            dh.download(this.$t('report.imReportLoyalty') + timeStamp)
          }
        })
      },
      changeHighChartsType () {
        if (this.chart === this.$t('report.imReportLine')) {
          this.chart = this.$t('report.imReportBar')
          this.highchartsDefaultOptions.chart.type = 'line'
        } else {
          this.chart = this.$t('report.imReportLine')
          this.highchartsDefaultOptions.chart.type = 'column'
        }
      },
      exportXls () {
        let data = {
          Method: 'exportImLoyaltyReport',
          Query: {
            reportType: this.id,
            user: this.$store.state.session.user._id,
            area: this.area,
            fromUrl: this.fromUrl
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImSessionTimeReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.webchat') + this.$t('report.imRecentLookTime') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$nextTick(() => {
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .look_time
    .provin
      width 600px
    .source
      .el-select
        width 600px
    .el-button
      margin 0 0 0 10px
    .source
      margin 14px 0
      .condi
        width 58px
        display inline-block
        line-height 30px
    .tab
      .table
        padding-bottom 20px
      .deploy
        .tip
          margin-left 0px
</style>
